/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package memory;

import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JOptionPane;
import javax.swing.Timer;

/**
 *
 * @author DAM110
 */
public class VentanaJuego extends javax.swing.JDialog implements ActionListener{

    VentanaPrincipal vp;
    Gestora g;
    Partida p;
    Carta[] cartas;
    int intentos = 0;
    int aciertos = 0;
    Timer temp;
    
    public VentanaJuego(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        this.setLocationRelativeTo(null);
        vp = (VentanaPrincipal) parent;
        g = vp.getG();
        p = g.getPartida();
        cartas = p.devuelvecartasAleatorias();
        temp = new Timer(1600/p.getD().getMultiplicador(),null);
        temp.setRepeats(false);        
        pCartas.setLayout(new java.awt.GridLayout(cartas.length/(2*p.getD().getMultiplicador()),(2*p.getD().getMultiplicador())));
        this.generarBotones();
    }

    /**
     * This method is called from within the constructor to initialize the form. WARNING: Do NOT
     * modify this code. The content of this method is always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        bComenzar = new javax.swing.JButton();
        pCartas = new javax.swing.JPanel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jLabel1.setText("Pulsa sobre Comenzar cuando estés listo");

        bComenzar.setText("Comenzar");
        bComenzar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                bComenzarActionPerformed(evt);
            }
        });

        pCartas.setLayout(new java.awt.GridLayout(1, 2));

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(pCartas, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                    .addGroup(layout.createSequentialGroup()
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addGap(128, 128, 128)
                                .addComponent(bComenzar))
                            .addGroup(layout.createSequentialGroup()
                                .addGap(78, 78, 78)
                                .addComponent(jLabel1)))
                        .addGap(0, 82, Short.MAX_VALUE)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addGap(24, 24, 24)
                .addComponent(jLabel1)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(bComenzar)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addComponent(pCartas, javax.swing.GroupLayout.DEFAULT_SIZE, 301, Short.MAX_VALUE)
                .addContainerGap())
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    private void bComenzarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_bComenzarActionPerformed
        
        for(Component c:pCartas.getComponents()){
            
            BotonCarta bc = (BotonCarta) c;
            bc.ponerReverso();
        }
        bComenzar.setEnabled(false);
    }//GEN-LAST:event_bComenzarActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(VentanaJuego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(VentanaJuego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(VentanaJuego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(VentanaJuego.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                VentanaJuego dialog = new VentanaJuego(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton bComenzar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JPanel pCartas;
    // End of variables declaration//GEN-END:variables

    @Override
    public void actionPerformed(ActionEvent e) {
        
        BotonCarta bc = (BotonCarta) e.getSource();
        BotonCarta anterior = null;
        
        for(Component c:pCartas.getComponents()){
            
            BotonCarta boton = (BotonCarta) c;
            if(boton.isMostrado()){
                anterior = boton;
                break;
            }
        }
        if(bc == anterior || temp.isRunning()){
            
        }else if(anterior == null){
            
            bc.ponerCara();
        }else{
            
            this.comprobar(bc, anterior);
        }
   
        
    }
    
    private void generarBotones(){
        
        for(Carta c:cartas){
            
            BotonCarta b = new BotonCarta(c.getRuta());
            b.addActionListener(this);
            pCartas.add(b);
        }
    }  
    
    private void comprobar(final BotonCarta bc,final BotonCarta ante){
        
        intentos++;
        
        if(bc.getRuta().equals(ante.getRuta())){
            bc.ponerCara();
            bc.setDisabledIcon(bc.getIcon());
            ante.setDisabledIcon(ante.getIcon());
            bc.setEnabled(false);
            ante.setEnabled(false);
            Sonido.reproducirSonido(Sonido.ACIERTO);
            aciertos++;
            this.comprobarTodoHecho();
        }else{
         Sonido.reproducirSonido(Sonido.ERROR);   
            ActionListener accion = new ActionListener() {
            @Override
          public void actionPerformed(ActionEvent evt) {
          bc.ponerReverso();
          ante.ponerReverso();
          temp.stop();
        }
        };
        
        temp.addActionListener(accion);
        bc.ponerCara();        
        ante.ponerCara();
        
            temp.start();
            
           
            
        }
        
    }
    
    private void comprobarTodoHecho(){
        
        if(aciertos == cartas.length/2){
            
            JOptionPane.showMessageDialog(this, "Has ganado");
            g.guardarPuntuacion(aciertos*100*p.getD().getMultiplicador(),intentos);
            g.guardarNombres();
            Sonido.pararSonido();
            new ConectarCliente(g.getPuntuacion()).start();
            this.dispose();
        }
    }
    
}
